<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>websocket通讯</title>
</head>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script type="text/javascript">
    <!--  连接-->
    var socket;
    var userName;
    // 连接
    function connect() {
        var socketUrl = "ws://localhost:4768/?id=" + $('#sendName').val();
        if (socket != null) {
            socket.close();
            socket = null;
        }
        socket = new WebSocket(socketUrl);
        //打开事件
        socket.onopen = function () {
            console.log("开始建立链接....")
        };
        //关闭事件
        socket.onclose = function () {
            console.log("websocket已关闭");
        };
        //发生了错误事件
        socket.onerror = function () {
            console.log("websocket发生了错误");
        };
        /**
         * 接收消息
         * @param msg
         */
        socket.onmessage = function (msg) {
            console.log(msg)
            var json = JSON.parse(msg.data);
            if (msg.msg != '连接成功') {
                $("#msgDiv").append('<p class="other" style="color:olivedrab;">' + json.sendName + '：'+json.msg+'</p>');
            }
        };
    }


    /**
     * 发送消息
     */
    function sendMessage() {
        var msg = $("#msg").val();
        if (msg == '' || msg == null) {
            alert("消息内容不能为空");
            return;
        }
        var receiver = $("#receiver").val();
        if (receiver == '' || receiver == null) {
            alert("接收人不能为空");
            return;
        }

        var sendName = $("#sendName").val();
        if (sendName == '' || sendName == null) {
            alert("发送人不能为空");
            return;
        }
        var msgObj = {
            "receiver": receiver,
            "sendName": sendName,
            "msg": msg
        };
        $("#msgDiv").append('<p class="user" style="color: red">' + sendName + '：'+msg+'</p>');
        try{
            socket.send(JSON.stringify(msgObj));
            $("#msg").val('');
        }catch (e) {
            alert("服务器内部错误");
        }
    }
</script>
<body>
用户名：<input type="text" id="sendName" value="李四">
<input type="button" value="连接" onclick="connect()" ><br>
发送者：<input type="text" id="sender" value="李四" ><br>
接受者：<input type="text" id="receiver" value="张三"><br><br>
消  息：<textarea id="msg"></textarea><br><input type="button" value="发送" onclick="sendMessage()"><br><br>

消息记录：<div id="msgDiv" style="border: 1px red solid;width: 400px;height: 200px"></div>
<br>

</body>
</html>